﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using CharitiesLib;

namespace Charities.Forms
{
    public partial class CustomOperationsSearch : Form
    {
        public CustomOperationsSearch(int id,Form m )
        {
            fo = m;
            userid = id;
            this.MdiParent = m;
            InitializeComponent();
        }
        Form fo = null;
        ModelContainer ctx = new ModelContainer();
        private int userid;
        string title = "نتيجة بحث عن المستحقين: ";
        
        public bool is_loaded = false;
        private void btn_Search_Click(object sender, EventArgs e)
        {
            title = " نتيجة بحث عن مستحقين وأقاربهم حيث : ";
            List<Person> tmpPersons = new List<Person>();
            List<Person> persons = new List<Person>();
            if (txb_worthyId.Text.Length > 0)
            {
                if (!title.Contains("المستحق ذو الرقم"))
                {
                    title += " المستحق ذو الرقم: " + txb_worthyId.Text + " ,";
                }
                int id;
                int.TryParse(txb_worthyId.Text, out id);
                if (id != 0)
                {
                    tmpPersons.AddRange(ctx.People.Where(c => c.WorthyId == id));
                    persons = tmpPersons;
                }
            }
            if (cbo_AgeConditions.SelectedIndex>=0)
            {
                if(!title.Contains("العمر"))
                title += "العمر:  "+cbo_AgeConditions.Text + " " + txb_Age.Text + " ,";
                int age;
                int.TryParse(txb_Age.Text, out age);
                DateTime agedate = DateTime.Now.AddYears(-age);
                if (tmpPersons.Count() > 0)
                {
                    if (cbo_AgeConditions.SelectedIndex == 0)
                    {
                        persons = tmpPersons.Where(c => c.DOB >= agedate).ToList();
                    }
                    else if (cbo_AgeConditions.SelectedIndex == 1)
                    {
                        persons = tmpPersons.Where(c => c.DOB <= agedate).ToList();
                    }
                    else
                    {
                        persons = tmpPersons.Where(c => c.DOB == agedate).ToList();
                    }
                }
                else
                {
                    if (cbo_AgeConditions.SelectedIndex == 0)
                    {
                        tmpPersons = ctx.People.Where(c => c.DOB >= agedate).ToList();
                    }
                    else if (cbo_AgeConditions.SelectedIndex == 1)
                    {
                        tmpPersons = ctx.People.Where(c => c.DOB <= agedate).ToList();
                    }
                    else
                    {
                        tmpPersons = ctx.People.Where(c => c.DOB == agedate).ToList();
                    }
                    persons = tmpPersons;
                }
            }

            if (cboFamilyCount.SelectedIndex >= 0)
            {
                if (!title.Contains("عدد أفراد العائلة"))
                title += "عدد أفراد العائلة:  " + cboFamilyCount.Text + " " + txbFamilyCount.Text + " ,";
                int fcount;
                int.TryParse(txbFamilyCount.Text, out fcount);
                if (tmpPersons.Count() > 0)
                {
                    if (cboFamilyCount.SelectedIndex == 0)
                    {
                        persons = tmpPersons.Where(w=>w.Worthy.People.Count() < fcount).ToList();
                    }
                    else if (cboFamilyCount.SelectedIndex == 1)
                    {
                        persons = tmpPersons.Where(c => c.Worthy.People.Count()> fcount).ToList();
                    }
                    else
                    {
                        persons = tmpPersons.Where(c => c.Worthy.People.Count() == fcount).ToList();
                    }
                }
                else
                {
                    if (cboFamilyCount.SelectedIndex == 0)
                    {
                        tmpPersons = ctx.People.Where(c => c.Worthy.People.Count() < fcount).ToList();
                    }
                    else if (cboFamilyCount.SelectedIndex == 1)
                    {
                        tmpPersons = ctx.People.Where(c => c.Worthy.People.Count() > fcount).ToList();
                    }
                    else
                    {
                        tmpPersons = ctx.People.Where(c => c.Worthy.People.Count() == fcount).ToList();
                    }
                    persons = tmpPersons;
                }
            }
            if ( cbo_Sex.SelectedIndex>0)
            {
                if (!title.Contains("الجنس"))
                title += "الجنس:  " + cbo_Sex.Text + " ," ;
                if (tmpPersons.Count() > 0)
                {
                    if (cbo_Sex.Text == "ذكر")
                    {
                        persons = tmpPersons.Where(c => c.Sex.Contains("كر")).ToList();
                    }
                    else
                    {
                        persons = tmpPersons.Where(c => c.Sex.Contains("ثى")).ToList();
                    }
                }
                else
                {
                    if (cbo_Sex.Text == "ذكر")
                    {
                        tmpPersons = ctx.People.Where(c => c.Sex.Contains("كر")).ToList();
                    }
                    else
                    {
                        tmpPersons = ctx.People.Where(c => c.Sex.Contains("ثى")).ToList();

                    }
                    persons = tmpPersons;
                }
            }
            if (cbo_WorthyType.Text.Length>0)
            {
                if (tmpPersons.Count() > 0)
                {
                    persons = tmpPersons.Where(c => c.Worthy.WorthyType.Name == cbo_WorthyType.Text).ToList();

                }
                else
                {
                    tmpPersons = ctx.People.Where(c => c.Worthy.WorthyType.Name == cbo_WorthyType.Text).ToList();
                    persons = tmpPersons;
                }
            }
            if (CboGrantedCart.Text.Length > 0)
            {
                if(!title.Contains("مستلم منحة"))
                title += "مستلم منحة:  " + CboGrantedCart.Text + " ," ;
                if (tmpPersons.Count() > 0)
                {
                    if (CboGrantedCart.SelectedValue != null)
                    {
                        int gid = (int)CboGrantedCart.SelectedValue;
                        if (gid > 0)
                        {
                          persons= tmpPersons
                              .Where(g => g.Worthy.Grants
                                  .Where(w=>w.Cart.Id==gid && w.IsDelivered==true)
                                  .Count() >0).ToList();
                          tmpPersons = persons;
                        }
                    }
                }
                else
                {
                    if (CboGrantedCart.SelectedValue != null)
                    {
                        int gid = (int)CboGrantedCart.SelectedValue;
                        if (gid > 0)
                        {
                            tmpPersons = ctx.People
                                .Where(g => g.Worthy.Grants
                                    .Where(w => w.Cart.Id == gid && w.IsDelivered == true)
                                    .Count() > 0).ToList();
                            persons = tmpPersons;
                        }
                    }
                }
            }
            if (cboGrantedSupply.Text.Length > 0)
            {
                if (!title.Contains("مستلم مادة"))
                    title += "مستلم مادة:  " + cboGrantedSupply.Text + " ,";
                if (tmpPersons.Count() > 0)
                {
                    if (cboGrantedSupply.SelectedValue != null)
                    {
                        int gid = (int)cboGrantedSupply.SelectedValue;
                        if (gid > 0)
                        {
                            persons = tmpPersons
                                .Where(g => g.Worthy.Grants
                                    .Where(w => (w.GrantDetails.Where(d=>d.SupplyId == gid && w.IsDelivered == true).Count()>0)
                                    || (w.Cart.CartDetails.Where(c=>c.SupplyId==gid &&w.IsDelivered==true).Count()>0))
                                    .Count() > 0).ToList();
                            tmpPersons = persons;
                        }
                    }
                }
                else
                {
                    if (cboGrantedSupply.SelectedValue != null)
                    {
                        int gid = (int)cboGrantedSupply.SelectedValue;
                        if (gid > 0)
                        {
                            tmpPersons = ctx.People
                                .Where(g => g.Worthy.Grants
                                   .Where(w => (w.GrantDetails.Where(d => d.SupplyId == gid && w.IsDelivered == true).Count() > 0)
                                    || (w.Cart.CartDetails.Where(c => c.SupplyId == gid && w.IsDelivered == true).Count() > 0))
                                    .Count() > 0).ToList();
                            persons = tmpPersons;
                        }
                    }
                }
            }

            if (txbFirstName.Text.Length > 0)
            {
                if(!title.Contains("الاسم"))
                title += "الاسم:  " + txbFirstName.Text + " ," ;
                if (tmpPersons.Count() > 0)
                {
                    persons = tmpPersons.Where(c => c.FirstName.Contains(txbFirstName.Text)).ToList();
                    tmpPersons = persons;
                }
                else
                {
                    tmpPersons = ctx.People.Where(c => c.FirstName.Contains(txbFirstName.Text)).ToList();
                    persons = tmpPersons;
                }
            }
            if (txbLastName.Text.Length > 0)
            {
                if(!title.Contains("اللقب"))
                title += "اللقب:  " + txbLastName.Text + " ," ;
                if (tmpPersons.Count() > 0)
                {
                    persons = tmpPersons.Where(c => c.LastName.Contains(txbLastName.Text)).ToList();
                    tmpPersons = persons;
                }
                else
                {
                    tmpPersons = ctx.People.Where(c => c.LastName.Contains(txbLastName.Text)).ToList();
                    persons = tmpPersons;
                }
            }
            if (txbJob.Text.Length > 0)
            {
                if (!title.Contains("العمل"))
                title += "العمل:  " + txbJob.Text + " ," ;
                if (tmpPersons.Count() > 0)
                {
                    persons = tmpPersons.Where(c => c.JobTitle.Contains(txbJob.Text)).ToList();
                    tmpPersons = persons;
                }
                else
                {
                    tmpPersons = ctx.People.Where(c => c.JobTitle.Contains(txbJob.Text)).ToList();
                    persons = tmpPersons;
                }
            }
            if (txbHealthStatus.Text.Length > 0)
            {
                if (!title.Contains("الوضع الصحي"))
                title += "الوضع الصحي:  " + txbHealthStatus.Text + " ," ;
                if (tmpPersons.Count() > 0)
                {
                    persons = tmpPersons.Where(c => c.HealthStatus.Contains(txbHealthStatus.Text)).ToList();
                    tmpPersons = persons;
                }
                else
                {
                    tmpPersons = ctx.People.Where(c => c.HealthStatus.Contains(txbHealthStatus.Text)).ToList();
                    persons = tmpPersons;
                }
            }

            if (txb_Address.Text.Length > 0)
            {
                if(!title.Contains("العنوان:"))
                title += "العنوان:  " + txb_Address.Text + " ," ;
                if (tmpPersons.Count() > 0)
                {
                    persons = tmpPersons.Where(c => c.Worthy.CurrentAddress.Contains(txb_Address.Text) || c.Worthy.OriginalAddress.Contains(txb_Address.Text)).ToList();
                    tmpPersons = persons;
                }
                else
                {
                    tmpPersons = ctx.People.Where(c => c.Worthy.CurrentAddress.Contains(txb_Address.Text) || c.Worthy.OriginalAddress.Contains(txb_Address.Text)).ToList();
                    persons = tmpPersons;
                }
                
            }
            if (dtp_FromDate.Value>DateTime.Now.AddYears(-50))
            {
                if (!title.Contains("من تاريخ"))
                title += "من تاريخ:  " + dtp_FromDate.Value.ToShortDateString()+ " ," ;
                if (tmpPersons.Count() > 0)
                {
                    persons = tmpPersons.Where(c => c.InsertDate >= dtp_FromDate.Value).ToList();
                    tmpPersons = persons;
                }
                else
                {
                    tmpPersons= ctx.People.Where(c => c.InsertDate >= dtp_FromDate.Value).ToList();
                    persons = tmpPersons;
                }
                
            }
            if (dtp_ToDate.Value>DateTime.Now.AddYears(-50))
            {
                if (!title.Contains("حتى تاريخ"))
                title += "حتى تاريخ:  " + dtp_ToDate.Value.ToShortDateString() + " ," ;
                if (tmpPersons.Count() > 0)
                {
                    persons = tmpPersons.Where(c => c.InsertDate <= dtp_ToDate.Value).ToList();
                    tmpPersons = persons;
                }
                else
                {
                    tmpPersons=ctx.People.Where(c => c.InsertDate <= dtp_ToDate.Value).ToList();
                    persons = tmpPersons;
                }
            }

            if (chk_isActive.CheckState==CheckState.Unchecked)
            {
                if (tmpPersons.Count() > 0)
                {
                    persons = tmpPersons.Where(c => c.Worthy.IsActive==true).ToList();
                    tmpPersons = persons;
                }
            }
            else if(chk_isActive.CheckState==CheckState.Checked)
            {
                if (!title.Contains("مرقن قيده"))
                title += "مرقن قيده "+",";

                if (tmpPersons.Count() > 0)
                {
                    persons = tmpPersons.Where(c => c.Worthy.IsActive == false).ToList();
                    tmpPersons = persons;
                }
                else
                {
                    tmpPersons = ctx.People.Where(c => c.Worthy.IsActive == true).ToList();
                persons = tmpPersons;
                }
            }
            if (chkGranted.CheckState==CheckState.Checked)
            {
                if (!title.Contains("مستلم منحة على الأقل"))
                title += "مستلم منحة على الأقل"+",";

                if (tmpPersons.Count() > 0)
                {
                    persons = tmpPersons.Where(c => c.Worthy.Grants.Where(g => g.IsDelivered == true).Count() > 0).ToList();
                    tmpPersons = persons;
                }
                else
                {
                    tmpPersons = ctx.People.Where(c => c.Worthy.Grants.Where(g => g.IsDelivered == true).Count() > 0).ToList();
                    persons = tmpPersons;
                }
            }
            else if (chkGranted.CheckState==CheckState.Unchecked)
            {
                if (!title.Contains("لم يستلم منحة واحدة على الأقل "))
                title += "لم يستلم منحة واحدة على الأقل "+",";

                if (tmpPersons.Count() > 0)
                {
                    persons = tmpPersons.Where(c => 
                        (c.Worthy.Grants.Where(g=>g.IsDelivered==true).Count()==0)
                        ||(c.Worthy.Grants.Count()==0)).ToList();
                    tmpPersons = persons;
                }
                else
                {
                    tmpPersons = ctx.People.Where(c => 
                        (c.Worthy.Grants.Where(g=>g.IsDelivered==true).Count()==0)
                        ||(c.Worthy.Grants.Count() == 0)).ToList();
                    persons = tmpPersons;
                }
            }
            List<Person> worths = new List<Person>();
            foreach (var i in persons)
            {
                Worthy w = ctx.Worthies.Single(s => s.Id == i.WorthyId);
                if (!worths.Exists(c=>c.WorthyId==i.WorthyId))
                {
                    if(persons.Exists(c => c.Id == w.PersonId))
                    worths.Add(persons.Single(c => c.Id == w.PersonId));
                    else
                    {
                        worths.Add(ctx.People.Single(c=>c.Id==w.PersonId &&c.WorthyId==w.Id));
                    }
                }
            }

            Dgv_Worthies.DataSource = worths;
            chkGranted.CheckState = CheckState.Indeterminate;
            chk_isActive.CheckState = CheckState.Indeterminate;
            dtp_FromDate.Value = DateTime.Now.AddYears(-113);
            dtp_ToDate.Value = DateTime.Now.AddYears(-113);
            tmpPersons = null;
            persons = null;
            
        }

        private void btn_AddGrant_Click(object sender, EventArgs e)
        {
            List<Worthy> worthies = new List<Worthy>();
            foreach (DataGridViewRow item in Dgv_Worthies.Rows)
            {
                if ((bool)item.Cells[1].Value==true)
                {
                    if( (int?)item.Cells[2].Value!=null)
                    {
                        int id = (int)item.Cells[2].Value;
                        Worthy w = ctx.Worthies.Single(c=>c.Id==id);
                        
                        if (w.IsActive)
                        {
                            worthies.Add(w);
                        }
                        else
                        {
                            Person p = ctx.People.Single(d=>d.Id==w.PersonId);
                            MessageBox.Show(" لا يمكن إضافة منحة للمستحق: "+p.FirstName+" "+p.LastName+" "+"لكونه مرقن القيد ");
                        }

                    }
                }
            }
            if (worthies.Count()>0)
            {

                GrantEditor g = new GrantEditor(userid, worthies, fo);
                g.Show();                
            }
        }

        private void CustomOperationsSearch_Load(object sender, EventArgs e)
        {
            is_loaded = true;
            // add this form to window list
            ((Forms.FormMDI)fo).addFormToWindowsList(this);
            User user = ctx.Users.Single(u => u.Id == userid);
            foreach (var Item in user.Role.Permissions)
            {
                switch (Item.Name.Trim())
                {
                    case "ADVANCED_SEARCH_GRANT":
                        btn_AddGrant.Visible = true;
                        break;
                    case "ADVANCED_SEARCH_WORTHY_DEACTIVATE":
                        btnDeactivateWorthy.Visible = true;
                        break;
                    case "ADVANCED_SEARCH_WORTHY_ACTIVATE":
                        btnActivateWorthy.Visible = true;
                        break;
                    case "ADVANCED_SEARCH_WORTHY_PRINT":
                        btnPrint.Visible = true;
                        break;
                    case "ADVANCED_SEARCH_WORTHY_DELETE":
                        btnPermenantDelete.Visible = true;
                        break;
                    default:
                        break;
                }
            }

        }

        private void btn_Deactivate_Worthy_Click(object sender, EventArgs e)
        {
            List<Worthy> worthies = new List<Worthy>();
            DialogResult result = MessageBox.Show("هل أنت متأكد من ترقين قيد المستحقين المحددين","تأكيد ترقين القيد",MessageBoxButtons.YesNo);
            if (result==DialogResult.Yes)
            {
                int itemCounts=0;
                foreach (DataGridViewRow item in Dgv_Worthies.Rows)
                {
                    if ((bool)item.Cells[1].Value == true)
                    {
                        if ((int?)item.Cells[2].Value != null)
                        {
                            int id = (int)item.Cells[2].Value;
                            Worthy w = ctx.Worthies.Single(c => c.Id == id);
                            w.IsActive = false;
                            ctx.SaveChanges();
                            itemCounts++;
                        }
                    }
                }
                MessageBox.Show(" تم ترقين قيد "+itemCounts+" مستحق ");
            }
        }
        bool toggle=false;
        private void DGV_Worthies_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            foreach (DataGridViewRow row in Dgv_Worthies.Rows)
            {
                if (toggle)
                    row.Cells[SelectedWorthiesColumns.Name].Value = false;
                else
                    row.Cells[SelectedWorthiesColumns.Name].Value = true;
            }

            if (toggle)
                toggle = false;
            else
                toggle = true;
        }

        private void CustomOperationsSearch_FormClosed(object sender, FormClosedEventArgs e)
        {
            is_loaded = false;
            // remove this form from windows list
            ((Forms.FormMDI)fo).removeFormFromWindowsList(this);
        }

        private void CustomOperationsSearch_Activated(object sender, EventArgs e)
        {
            // activate this form and add it windows list as activate one
            ((Forms.FormMDI)this.MdiParent).activateWindow(this);
        }

        private void btn_Dispose_Click(object sender, EventArgs e)
        {
            Close();
            is_loaded = false;
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            List<Worthy> worthisLis=new List<Worthy>();
            foreach (DataGridViewRow row in Dgv_Worthies.Rows)
            {
                if (row.Cells[2].Value != null)
                {
                    int id = (int)row.Cells[2].Value;
                    if (id > 0)
                    {
                        Worthy wor = ctx.Worthies.Single(w => w.Id == id);
                        worthisLis.Add(wor);
                    }
                }
            }
            CustomSearchPrintForm cs = new CustomSearchPrintForm(userid,fo,worthisLis,title);
            cs.Show();
            
        }

        private void CboGrantedCart_DropDown(object sender, EventArgs e)
        {
            CboGrantedCart.DataSource =ctx.Carts.ToList();
            CboGrantedCart.DisplayMember = "Name";
            CboGrantedCart.ValueMember = "Id";
        }

        private void cboGrantedSupply_DropDown(object sender, EventArgs e)
        {
            cboGrantedSupply.DataSource = ctx.Supplies.ToList();
            cboGrantedSupply.DisplayMember = "Name";
            cboGrantedSupply.ValueMember = "Id";
        }

        private void cbo_WorthyType_DropDown(object sender, EventArgs e)
        {

            cbo_WorthyType.DataSource = ctx.WorthyTypes.ToList();
        }

        private void Dgv_Worthies_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                if (Dgv_Worthies.Rows[e.RowIndex].Cells[2].Value != null)
                {
                    int worthyId = (int)Dgv_Worthies.Rows[e.RowIndex].Cells[2].Value;
                    if (worthyId > 0)
                    {
                        MainWindow m =null;
                        if (m != null && m.is_loaded)
                        {
                            m.Activate();
                        }
                        else
                        {
                            m = new MainWindow(userid, fo, false, worthyId);
                            m.Show();
                        }
                    }
                }
            }
        }

        private void btnActivateWorthy_Click(object sender, EventArgs e)
        {
            List<Worthy> worthies = new List<Worthy>();
            DialogResult result = MessageBox.Show("هل أنت متأكد من ازلة ترقين قيد المستحقين المحددين", "تأكيد إزلة ترقين القيد", MessageBoxButtons.YesNo);
            if (result == DialogResult.Yes)
            {
                int itemCounts = 0;
                foreach (DataGridViewRow item in Dgv_Worthies.Rows)
                {
                    if ((bool)item.Cells[1].Value == true)
                    {
                        if ((int?)item.Cells[2].Value != null)
                        {
                            int id = (int)item.Cells[2].Value;
                            Worthy w = ctx.Worthies.Single(c => c.Id == id);
                            w.IsActive = true;
                            ctx.SaveChanges();
                            itemCounts++;
                        }
                    }
                }
                MessageBox.Show(" تم إزلة ترقين قيد " + itemCounts + " مستحق ");
            }
        }

        private void btnPermenantDelete_Click(object sender, EventArgs e)
        {
            List<Worthy> worthies = new List<Worthy>();
            DialogResult result = MessageBox.Show("الحذف النهائي لا يمكن التراجع عنه هل أنت متأكد من حذف المستحقين المحددين (لن يتم حذف العناصر المستلمة لمنح)", "تأكيد حذف القيد", MessageBoxButtons.YesNo,MessageBoxIcon.Warning);
            if (result == DialogResult.Yes)
            {
                int itemCounts = 0;
                foreach (DataGridViewRow item in Dgv_Worthies.Rows)
                {
                    if ((bool)item.Cells[1].Value == true)
                    {
                        if ((int?)item.Cells[2].Value != null)
                        {
                            int id = (int)item.Cells[2].Value;
                            Worthy w = ctx.Worthies.Single(c => c.Id == id);
                            if (w.Grants.Where(g => g.IsDelivered == true).Count() == 0)
                            {
                                ctx.Worthies.Remove(w);
                                ctx.SaveChanges();
                                itemCounts++;
                            }
                        }
                    }
                }
                MessageBox.Show(" تم حذف  " + itemCounts + " مستحق حذفاً نهائياً ");
            }
        }
    
    }
}
